import { editProfile, logout ,enterOnlinePractice ,entertoDoPractice,openLearnTrack,setupUserProfile} from './auth.js';
import { openModal,createCourse, closeCreateCourseModal, saveCourse, viewCourses, closeViewCoursesModal, searchCourses , openCoursePreviewModal ,closeCoursePreviewModal,openSelectCourseModal,closeSelectCourseModal,selectCourse,viewCourseSchedule,dropCourse} from './course.js';
import { checkRoleAndAddChapter, closeAddChapterModal, addNewChapter, checkRoleAndDeleteChapter, closeDeleteChapterModal, deleteChapter, openViewChaptersModal, closeViewChaptersModal ,generateUniqueChapterId,isChapterTitleDuplicate} from './chapter.js';
import { new_openModal,new_openViewResourcesModal,openUploadResourceModal, closeUploadResourceModal, uploadResource, viewResources, openViewResourcesModal ,closeViewResourcesModal ,downloadResource, openAllVersionsModal , previewResource , getResourceInfo , getUserClass ,closeAllVersionsModal,filterResources,generateUniqueResourceId} from './resource.js';
import { createClass , closeCreateClassModal , saveClass , joinClass , closeJoinClassModal , confirmJoinClass , manageClasses} from './class.js';
import { openCodeLinesModal , closeCodeLinesModal} from './codeline.js';
window.editProfile = editProfile;
window.logout = logout;
window.createCourse = createCourse;
window.closeCreateCourseModal = closeCreateCourseModal;
window.saveCourse = saveCourse;
window.viewCourses = viewCourses;
window.closeViewCoursesModal = closeViewCoursesModal;
window.searchCourses = searchCourses;
window.checkRoleAndAddChapter = checkRoleAndAddChapter;
window.closeAddChapterModal = closeAddChapterModal;
window.addNewChapter = addNewChapter;
window.checkRoleAndDeleteChapter = checkRoleAndDeleteChapter;
window.closeDeleteChapterModal = closeDeleteChapterModal;
window.deleteChapter = deleteChapter;
window.openViewChaptersModal = openViewChaptersModal;
window.closeViewChaptersModal = closeViewChaptersModal;
window.generateUniqueChapterId = generateUniqueChapterId;
window.isChapterTitleDuplicate = isChapterTitleDuplicate;
window.openUploadResourceModal = openUploadResourceModal;
window.closeUploadResourceModal = closeUploadResourceModal;
window.uploadResource = uploadResource;
window.downloadResource = downloadResource;
window.viewResources = viewResources;
window.closeViewResourcesModal = closeViewResourcesModal;
window.openViewResourcesModal = openViewResourcesModal;
window.openCoursePreviewModal = openCoursePreviewModal;
window.closeCoursePreviewModal = closeCoursePreviewModal;
window.openSelectCourseModal = openSelectCourseModal;
window.closeSelectCourseModal = closeSelectCourseModal;
window.selectCourse = selectCourse;
window.viewCourseSchedule = viewCourseSchedule;
window.dropCourse = dropCourse;
window.createClass = createClass;
window.closeCreateClassModal = closeCreateClassModal;
window.saveClass = saveClass;
window.joinClass = joinClass;
window.closeJoinClassModal = closeJoinClassModal;
window.confirmJoinClass = confirmJoinClass;
window.manageClasses = manageClasses;
window.openAllVersionsModal = openAllVersionsModal;
window.previewResource = previewResource;
window.getResourceInfo = getResourceInfo;
window.getUserClass = getUserClass;
window.closeAllVersionsModal = closeAllVersionsModal;
window.filterResources = filterResources;
window.openCodeLinesModal = openCodeLinesModal;
window.closeCodeLinesModal = closeCodeLinesModal;
window.enterOnlinePractice = enterOnlinePractice;
window.entertoDoPractice = entertoDoPractice;
window.openLearnTrack = openLearnTrack;
//window.openModal = openModal;
window.new_openModal = new_openModal;
window.new_openViewResourcesModal = new_openViewResourcesModal;
window.setupUserProfile = setupUserProfile;
//动态按钮显示
document.addEventListener('DOMContentLoaded', async () => {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    
    if (!username) {
        console.error('未获取到用户信息，URL参数中缺少username');
        return;
    }
    
    try {
        await setupUserProfile(username);
        // 获取用户信息
        const userResponse = await fetch(`/user-info?username=${username}`);
        const userData = await userResponse.json();
        const isTeacher = userData.role === '教师';
        
        // 设置当前日期和星期
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth() + 1;
        const day = now.getDate();
        const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const weekday = weekdays[now.getDay()];
        const dateDisplay = document.getElementById('current-date');
        
        // 如果是学生，获取班级信息
        if (!isTeacher) {
            try {
                // 获取用户所在班级
                const classResponse = await fetch(`/get-user-class?username=${username}`);
                const classData = await classResponse.json();
                //console.log('当前用户所在班级:', classData);
                if (classData && classData.class_name) {
                    // 显示日期、星期和班级名称
                    if(dateDisplay)
                    dateDisplay.textContent = `${year}年${month}月${day}日，${weekday} | 班级: ${classData.class_name}`;
                } else {
                    if(dateDisplay)
                    dateDisplay.textContent = `${year}年${month}月${day}日，${weekday} | 未加入班级`;
                }
            } catch (error) {
                console.error('获取班级信息失败:', error);
                dateDisplay.textContent = `${year}年${month}月${day}日，${weekday}`;
            }
        } else {
            // 教师只显示日期和星期
            dateDisplay.textContent = `${year}年${month}月${day}日，${weekday}`;
        }
        
        // 根据角色显示/隐藏按钮
        const buttons = [
            'createCourseButton', 'viewCourseScheduleButton', 'createClassButton',
            'joinClassButton', 'manageClassesButton', 'onlinePracticeButton',
            'todoPracticeButton', 'learnTrackButton','tutorManageButton'
        ];
        
        buttons.forEach(buttonId => {
            const button = document.getElementById(buttonId);
            if (button) {
                if (
                    (isTeacher && [
                        'createCourseButton', 'createClassButton', 'manageClassesButton', 'onlinePracticeButton','tutorManageButton'
                    ].includes(buttonId)) ||
                    (!isTeacher && [
                        'viewCourseScheduleButton', 'joinClassButton', 'todoPracticeButton', 'learnTrackButton'
                    ].includes(buttonId))
                ) {
                    button.style.display = '';
                    button.style.visibility = 'visible';
                } else {
                    button.style.display = 'none';
                }
            }
        });
        await fetchDashboardStats();
    } catch (error) {
        console.error('获取用户信息失败:', error);
    }
});
const tutorManageButton = document.getElementById('tutorManageButton');
if(tutorManageButton){
tutorManageButton.addEventListener('click', () => {
    window.location.href = 'tutor-manage.html'+ window.location.search;
});
}
// 在DOMContentLoaded事件监听器中添加以下代码
async function fetchDashboardStats() {
    try {
        const response = await fetch('/dashboard-stats');
        const data = await response.json();
        
        if (data.success) {
            // 更新DOM元素
            document.querySelector('.bg-blue-100 + div p.text-lg').textContent = data.data.courses;
            document.querySelector('.bg-green-100 + div p.text-lg').textContent = data.data.resources;
            document.querySelector('.bg-purple-100 + div p.text-lg').textContent = data.data.practices;
            document.querySelector('.bg-yellow-100 + div p.text-lg').textContent = data.data.users;
        } else {
            console.error('获取统计数据失败:', data.message);
        }
    } catch (error) {
        //console.error('请求统计数据失败:', error);
    }
}